﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

using LuxDiner.Model.Accounts;
using LuxDiner.Logic.Accounts;
namespace LuxDiner.Web.Global
{
    public class WebContext
    {
        private const string CACHE_User = "LuxDiner_User_";

        public static HttpContext CurrentContext
        {
            get
            {
                return HttpContext.Current;
            }
            set
            {
                HttpContext.Current = value;
            }
        }

        public static HttpRequest Request
        {
            get
            {
                return CurrentContext.Request;
            }
        }

        public static HttpResponse Response
        {
            get
            {
                return CurrentContext.Response;
            }
        }

        public static UserModel CurrentUser
        {
            get
            {
                UserModel user = null;
                try
                {
                    var guid = CurrentContext.User.Identity.Name;
                    if (!string.IsNullOrEmpty(guid))
                    {
                        user = (UserModel)CurrentContext.Cache[CACHE_User + guid];
                        if (user == null)
                        {
                            user =UserLogic.GetUser(guid);
                            CurrentContext.Cache[CACHE_User + user.Guid.ToString()] = user;
                        }
                    }
                }
                catch { }
                return user;
            }
            set
            {
                if (value != null)
                {
                    CurrentContext.Cache[CACHE_User + value.Guid.ToString()] = value;
                }
            }
        }

        public static void LogOut()
        {
            var userName = CurrentContext.User.Identity.Name;
            if (!string.IsNullOrEmpty(userName))
                CurrentContext.Cache.Remove(CACHE_User + userName);
            System.Web.Security.FormsAuthentication.SignOut();
        }
    }
}
